# == Schema Information
# Schema version: 38
#
# Table name: event_comments
#
#  id           :integer(11)     not null, primary key
#  event_id     :integer(11)
#  user_id      :integer(11)
#  title        :string(255)
#  content      :text
#  content_html :text
#  created_at   :datetime
#  updated_at   :datetime
#

class EventComment < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
  validates_presence_of :content
  # before_save :insert_img # 直接修改了 white_list_formmatted_content
  format_attribute :content
  
  def editable_by?(user)
    user!=:false && user.id == user_id
  end
  
  def self.all(limit=10)
    self.find(:all,
              :limit => limit,
              :order => "event_comments.created_at desc",
              :select => "event_comments.*, users.login as user_login, users.avatar_url as user_avatar, events.title as event_title",
              :joins => "join users on users.id=event_comments.user_id join events on events.id=event_comments.event_id")
  end
  
  protected
  
  def insert_img
    self.content = self.content.gsub(/\<图片\d+\>/) {|s| "<img src='#{Photo.find(s.scan(/\d+/)[0]).public_filename(:small)}'/>" }
  end

  def self.archives
    date_func = "extract(year from created_at) as year,extract(month from created_at) as month"
    
    counts = EventComment.find_by_sql(["select count(*) as count, #{date_func} from event_comments where created_at < ? group by year,month order by year asc,month asc",Time.now])
    
    sum = 0
    result = counts.map do |entry|
      sum += entry.count.to_i
      {
        :name => entry.year + "年" + entry.month + "月",
        :month => entry.month.to_i,
        :year => entry.year.to_i,
        :delta => entry.count,
        :sum => sum
      }
    end
    return result.reverse
  end
end
